package com.nsgf.library.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;

import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.appcompat.app.AlertDialog;

import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.DecimalFormat;

import com.nsgf.library.R;
import com.nsgf.skjz.utils.Kits;

/**
 * ****************************
 * 项目名称：demo_sc
 * Authro:gc
 * 创建时间：2020/1/21 13:50
 * 用户：
 * ****************************
 **/
public class UpdateService {
    private static final String TAG = "UpdateService";
    private DownloadManager mDownloadManager;
    private Activity mContext;
    private long downloadId;
    private String apkName = Kits.Date.getTimeStame().concat("_skjz.apk");

    public UpdateService() {

    }

    public UpdateService(Activity context) {
        mContext = context;
    }

    public void download(String url, String name) {
        final String packageName = "com.android.providers.downloads";
        int state = mContext.getPackageManager().getApplicationEnabledSetting(packageName);
        //检测下载管理器是否被禁用
        if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext).setTitle("温馨提示").setMessage
                    ("系统下载管理器被禁止，需手动打开").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    try {
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        intent.setData(Uri.parse("package:" + packageName));
                        mContext.startActivity(intent);
                    } catch (ActivityNotFoundException e) {
                        Intent intent = new Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
                        mContext.startActivity(intent);
                    }
                }
            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.create().show();
        } else {
            //正常下载流程
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            request.setAllowedOverRoaming(false);

            //通知栏显示
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setTitle("栖霞智慧水务");
            request.setDescription("正在下载中...");
            request.setVisibleInDownloadsUi(true);

            //设置下载的路径 - 根据Android版本选择合适的路径
            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    // Android 10+ 使用应用私有目录，不需要存储权限
                    File downloadDir = mContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
                    if (downloadDir != null && downloadDir.exists()) {
                        request.setDestinationInExternalFilesDir(mContext, Environment.DIRECTORY_DOWNLOADS, apkName);
                    } else {
                        // 如果私有目录不可用，使用应用内部存储
                        File internalDir = new File(mContext.getFilesDir(), "downloads");
                        if (!internalDir.exists()) {
                            internalDir.mkdirs();
                        }
                        request.setDestinationUri(Uri.fromFile(new File(internalDir, apkName)));
                    }
                } else {
                    // Android 9 及以下使用公共目录，需要存储权限
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        // 检查权限
                        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                != PackageManager.PERMISSION_GRANTED) {
                            Toast.makeText(mContext, "需要存储权限才能下载，请授予权限后重试", Toast.LENGTH_LONG).show();
                            return;
                        }
                    }
                    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, apkName);
                }
            } catch (Exception e) {
                // 如果设置路径失败，使用默认路径
                Toast.makeText(mContext, "设置下载路径失败，将使用默认路径", Toast.LENGTH_SHORT).show();
                request.setDestinationInExternalFilesDir(mContext, Environment.DIRECTORY_DOWNLOADS, apkName);
            }

            //获取DownloadManager
            mDownloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
            downloadId = mDownloadManager.enqueue(request);
            startQuery();

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
                mContext.registerReceiver(mReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE), Context.RECEIVER_NOT_EXPORTED);
            } else {
                mContext.registerReceiver(mReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
            }
        }
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            checkStatus();
        }
    };

    /**
     * 检查下载状态
     */
    @SuppressLint("Range")
    private void checkStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(downloadId);
        Cursor cursor = mDownloadManager.query(query);
        if (cursor.moveToFirst()) {
            int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                //下载暂停
                case DownloadManager.STATUS_PAUSED:
                    break;
                //下载延迟
                case DownloadManager.STATUS_PENDING:
                    break;
                //正在下载
                case DownloadManager.STATUS_RUNNING:
                    int mDownload_all = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                    int mDownload_so_far = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                    Message msg = Message.obtain();
                    if (mDownload_all > 0) {
                        msg.what = 1001;
                        msg.arg1 = mDownload_so_far;
                        msg.arg2 = mDownload_all;
                        mHandler.sendMessage(msg);
                    }
                    break;
                //下载完成
                case DownloadManager.STATUS_SUCCESSFUL:
                    stopQuery();
                    installAPK();
                    mContext.finish();
                    break;
                //下载失败
                case DownloadManager.STATUS_FAILED:
                    Toast.makeText(mContext, "下载失败", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
        cursor.close();
    }


    /**
     * 7.0兼容 - 改进版本，解决不同机型解析包错误
     */
    private void installAPK() {
        try {
            // 尝试多个可能的下载路径
            File apkFile = findApkFile();
            if (apkFile == null || !apkFile.exists()) {
                Toast.makeText(mContext, "APK文件未找到，请检查下载是否完成", Toast.LENGTH_LONG).show();
                return;
            }

            // 改进的文件完整性检查
            if (!isValidApkFile(apkFile)) {
                Toast.makeText(mContext, "APK文件损坏或不完整，请重新下载", Toast.LENGTH_LONG).show();
                return;
            }

            // 检查FileProvider配置 - 如果检查失败，仍然尝试安装
            if (!isFileProviderConfigured()) {
                Log.w(TAG, "FileProvider configuration check failed, but continuing with installation");
                // 不阻止安装，只是记录警告
            }

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                try {
                    Uri apkUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", apkFile);
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                } catch (Exception e) {
                    Log.e(TAG, "FileProvider failed: " + e.getMessage());
                    // 如果FileProvider失败，尝试使用ACTION_INSTALL_PACKAGE
                    intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    try {
                        Uri apkUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", apkFile);
                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        intent.setData(apkUri);
                    } catch (Exception ex) {
                        Log.e(TAG, "FileProvider failed again: " + ex.getMessage());
                        // 最后的备用方案
                        installAPKWithPackageManager(apkFile);
                        return;
                    }
                }
            } else {
                intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            }

            // 检查是否有应用可以处理这个Intent
            if (intent.resolveActivity(mContext.getPackageManager()) != null) {
                mContext.startActivity(intent);
            } else {
                // 如果没有应用可以处理，尝试使用PackageInstaller
                installAPKWithPackageManager(apkFile);
            }

        } catch (Exception e) {
            Log.e(TAG, "Install APK failed: " + e.getMessage());
            Toast.makeText(mContext, "安装失败：" + e.getMessage(), Toast.LENGTH_LONG).show();

            // 尝试备用安装方法
            try {
                File apkFile = findApkFile();
                if (apkFile != null && apkFile.exists()) {
                    installAPKWithPackageManager(apkFile);
                }
            } catch (Exception ex) {
                Log.e(TAG, "Backup install method failed: " + ex.getMessage());
                Toast.makeText(mContext, "所有安装方法都失败了，请手动安装", Toast.LENGTH_LONG).show();
            }
        }
    }

    /**
     * 检查APK文件是否有效 - 简化版本，避免误判
     */
    private boolean isValidApkFile(File apkFile) {
        try {
            // 检查文件大小 - 降低阈值，避免误判
            long fileSize = apkFile.length();
            if (fileSize < 100 * 1024) { // 小于100KB认为不完整
                Log.w(TAG, "APK file too small: " + fileSize + " bytes");
                return false;
            }

            // 检查文件扩展名
            if (!apkFile.getName().toLowerCase().endsWith(".apk")) {
                Log.w(TAG, "File is not an APK: " + apkFile.getName());
                return false;
            }

            // 检查文件是否可读
            if (!apkFile.canRead()) {
                Log.w(TAG, "APK file is not readable");
                return false;
            }

            // 简单的文件头检查 - 只检查前几个字节是否为ZIP格式
            try (FileInputStream fis = new FileInputStream(apkFile)) {
                byte[] header = new byte[4];
                int bytesRead = fis.read(header);
                if (bytesRead < 4) {
                    Log.w(TAG, "APK file too short to read header");
                    return false;
                }

                // ZIP文件头应该是 PK\x03\x04 或类似的
                // 但为了兼容性，我们只做最基本的检查
                if (header[0] == 0x50 && header[1] == 0x4B) { // PK
                    Log.d(TAG, "APK file validation passed - basic ZIP header check");
                    return true;
                } else {
                    // 如果ZIP头检查失败，仍然允许安装，因为某些APK可能有不同的格式
                    Log.w(TAG, "APK file ZIP header check failed, but allowing installation anyway");
                    return true;
                }
            } catch (IOException e) {
                Log.w(TAG, "Error reading APK file header: " + e.getMessage() + ", but allowing installation");
                return true; // 即使读取头失败，也允许安装
            }

        } catch (Exception e) {
            Log.w(TAG, "Exception during APK validation: " + e.getMessage() + ", but allowing installation");
            return true; // 出现异常时，为了兼容性，仍然允许安装
        }
    }

    /**
     * 检查FileProvider是否已配置 - 简化版本
     */
    private boolean isFileProviderConfigured() {
        try {
            // 尝试获取FileProvider的Authority
            String authority = mContext.getPackageName() + ".fileprovider";
            File tempFile = new File(mContext.getCacheDir(), "temp_test");
            tempFile.createNewFile();

            Uri uri = FileProvider.getUriForFile(mContext, authority, tempFile);
            tempFile.delete();

            return uri != null;
        } catch (Exception e) {
            Log.w(TAG, "FileProvider configuration check failed: " + e.getMessage());
            // 为了兼容性，返回true，让安装流程继续
            return true;
        }
    }

    /**
     * 查找APK文件
     */
    private File findApkFile() {
        String[] possiblePaths = {
                // 应用私有目录（Android 10+ 优先）
                mContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) != null ?
                        mContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getPath() : null,
                // 应用内部存储目录
                new File(mContext.getFilesDir(), "downloads").getPath(),
                // 公共下载目录
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath(),
                // 其他可能的下载目录
                Environment.getExternalStorageDirectory().getPath() + "/Download",
                Environment.getExternalStorageDirectory().getPath() + "/Downloads",
                Environment.getExternalStorageDirectory().getPath() + "/download",
                Environment.getExternalStorageDirectory().getPath() + "/downloads"
        };

        for (String path : possiblePaths) {
            if (path != null) {
                File file = new File(path, apkName);
                if (file.exists() && file.canRead()) {
                    Log.d(TAG, "Found APK file: " + file.getAbsolutePath());
                    return file;
                }
            }
        }

        Log.w(TAG, "APK file not found in any of the expected paths");
        return null;
    }

    /**
     * 使用PackageManager安装APK（备用方案）
     */
    private void installAPKWithPackageManager(File apkFile) {
        try {
            Log.d(TAG, "Attempting to install APK with PackageManager: " + apkFile.getAbsolutePath());

            Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                try {
                    Uri apkUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", apkFile);
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    intent.setData(apkUri);
                } catch (Exception e) {
                    Log.e(TAG, "FileProvider failed in PackageManager method: " + e.getMessage());
                    // 如果FileProvider失败，尝试使用file:// URI（仅用于测试）
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                        intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                    } else {
                        throw e;
                    }
                }
            } else {
                intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            }

            mContext.startActivity(intent);
            Log.d(TAG, "PackageManager install intent started successfully");

        } catch (Exception e) {
            Log.e(TAG, "PackageManager install failed: " + e.getMessage());
            Toast.makeText(mContext, "无法启动安装程序，请手动安装", Toast.LENGTH_LONG).show();

            // 最后的备用方案：提示用户手动安装
            showManualInstallDialog(apkFile);
        }
    }

    /**
     * 显示手动安装对话框
     */
    private void showManualInstallDialog(File apkFile) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext)
                .setTitle("安装提示")
                .setMessage("自动安装失败，请手动安装APK文件。\n\n文件路径：" + apkFile.getAbsolutePath())
                .setPositiveButton("复制路径", (dialog, which) -> {
                    // 复制文件路径到剪贴板
                    android.content.ClipboardManager clipboard =
                            (android.content.ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                    android.content.ClipData clip = android.content.ClipData.newPlainText("APK路径", apkFile.getAbsolutePath());
                    clipboard.setPrimaryClip(clip);
                    Toast.makeText(mContext, "路径已复制到剪贴板", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", (dialog, which) -> dialog.dismiss());

        builder.create().show();
    }

    private final QueryRunnable mQueryProgressRunnable = new QueryRunnable();
    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1001) {
                if (progressBar != null) {
                    progressBar.setProgress(msg.arg1);
                    DecimalFormat df = new DecimalFormat("#####0.00");
                    try {
                        tv_progress.setText(df.format(Double.parseDouble(String.valueOf(msg.arg1)) / (Double.parseDouble(String.valueOf(msg.arg2))) * 100) + "%");
                    } catch (Exception e) {
                        e.getMessage();
                    }
                    progressBar.setMax(msg.arg2);
                }
            }
        }
    };

    //更新下载进度
    private void startQuery() {
        if (downloadId != 0) {
            showUpdataVersion();
            mHandler.post(mQueryProgressRunnable);
        }
    }

    //查询下载进度
    private class QueryRunnable implements Runnable {
        @Override
        public void run() {
            checkStatus();
            showUpdataVersion();
            mHandler.postDelayed(mQueryProgressRunnable, 100);
        }
    }

    //停止查询下载进度
    private void stopQuery() {
        mHandler.removeCallbacks(mQueryProgressRunnable);
    }

    //下载停止同时删除下载文件
    private void removeDownload() {
        if (mDownloadManager != null) {
            mDownloadManager.remove(downloadId);
        }
    }

    private Dialog dialogDownload;
    ProgressBar progressBar;
    TextView tv_progress;

    private void showUpdataVersion() {
        if (dialogDownload == null) {
            dialogDownload = new Dialog(mContext, R.style.dialog_style);
            View view = View.inflate(mContext, R.layout.dialog_updata_version_download, null);
            progressBar = view.findViewById(R.id.progressBar);
            tv_progress = view.findViewById(R.id.tv_progress);
            dialogDownload.setContentView(view);
        }
        dialogDownload.setCancelable(false);
        dialogDownload.show();

    }
}